package com.zbkj.crmeb.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.constants.Constants;
import com.crmeb.core.common.CommonApiResult;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.OutOrderSourceEnum;
import com.zbkj.crmeb.order.request.*;
import com.zbkj.crmeb.order.response.JkyOrderResponse;
import com.zbkj.crmeb.order.response.SeatentResponse;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.service.StoreOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("jkyApi/order")
@Api(tags = "吉客云订阅")
public class JkyApiOrderController {
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private IChannelMerchantService channelMerchantService;

    /** **** **** ****  吉客云订单推送业务 ** **** ********/
    public static final String DELIVERYORDER_CREATE = "deliveryorder.create";

    public static final String SINGLEITEM_SYNCHRONIZE = "singleitem.synchronize";

    public static final String ORDER_CANCEL = "order.cancel";
    /**
     * 吉客云订单推送
     * @author
     * @since
     */
    @ApiOperation(value = "吉客云订单推送")
    @RequestMapping(value = "/push", method = RequestMethod.POST)
    public JkyOrderResponse push(HttpServletRequest request) throws Exception{

        log.info("-----------吉客云订单推送接收到-method {}-----------", request.getParameter("method"));
        log.info("-----------吉客云订单推送接收到-content {}-----------", request.getParameter("content"));

        JkyOrderResponse result = new JkyOrderResponse();
        result.setFlag("failure");
        result.setCode(400);
        result.setCreateTime(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));

        try {

            String method = (URLDecoder.decode(request.getParameter("method"), "utf-8"));

            if(DELIVERYORDER_CREATE.equals(method)){
                JkyOrderPushRequest  jkyOrderPushData = new JkyOrderPushRequest();
                String  content = URLDecoder.decode(request.getParameter("content"), "utf-8");
                jkyOrderPushData.setContent(JSONObject.parseObject(content, JkyOrderPushRequest.Content.class));

                if(jkyOrderPushData.getContent()!=null){

                    JkyOrderPushRequest.DeliveryOrder deliveryOrder = jkyOrderPushData.getContent().getDeliveryOrder();
                    result.setDeliveryOrderId(deliveryOrder.getDeliveryOrderCode());
                    List<JkyOrderPushRequest.OrderLines> orderLines = jkyOrderPushData.getContent().getOrderLines();

                    StoreOrder storeOrder = storeOrderService.getByOrderId("OT" + deliveryOrder.getDeliveryOrderCode());
                    if(null != storeOrder){
                        log.info("--------------- 推送外部订单已经存在,orderId:{} ---------------", storeOrder.getOrderId());
                        result.setMessage("订单已经存在！");
                        return result;
                    }

                    // 订单推送
                    OutOrderRequest outOrderRequest = buildJkyOutOrder(deliveryOrder,orderLines);
                    // TODO 所属商户, 需要配置
                    ChannelMerchant channelMerchant = channelMerchantService.getById(18);

                    if(storeOrderService.pushOutOrder(outOrderRequest, channelMerchant)){
                        result.setFlag("success");
                        result.setCode(0);
                        result.setMessage("订单保存成功！");

                        return result;
                    }

                }

            }else if(SINGLEITEM_SYNCHRONIZE.equals(method))
            {
                JkyItemSynRequest  jkyItemSynData = new JkyItemSynRequest();
                String  content = URLDecoder.decode(request.getParameter("content"), "utf-8");
                jkyItemSynData.setContent(JSONObject.parseObject(content, JkyItemSynRequest.Content.class));

                if(storeOrderService.CheckJkyItemSyn(jkyItemSynData)){
                    result.setFlag("success");
                    result.setCode(0);
                    result.setMessage("订单取消成功！");

                    return result;
                }else
                {
                    result.setMessage("商品不存在！");

                    return result;
                }

            }else if(ORDER_CANCEL.equals(method))
            {
                JkyCancelRequest  jkyCancelData = new JkyCancelRequest();
                String  content = URLDecoder.decode(request.getParameter("content"), "utf-8");
                jkyCancelData.setContent(JSONObject.parseObject(content, JkyCancelRequest.Content.class));

                StoreOrder storeOrder = storeOrderService.getByOrderId("OT" + jkyCancelData.getContent().getOrderCode());
                if(null == storeOrder){
                    log.info("--------------- 外部订单不存在,orderId:{} ---------------", jkyCancelData.getContent().getOrderCode());
                    result.setMessage("订单已经存在！");
                    return result;
                }

                if( storeOrderService.jkyCancelOrder(storeOrder.getId())){
                    result.setFlag("success");
                    result.setCode(0);
                    result.setMessage("商品同步成功！");

                    return result;
                }else
                {
                    result.setMessage("商品不存在！");

                    return result;
                }

            }else
            {

                log.error("--------------- 吉客云订单推送 getMethod: {} 错误 暂不处理！ --------------",method);

                result.setMessage("其他业务暂不处理！");

                return result;
            }

        }catch (Exception e){
            e.printStackTrace();
            result.setMessage(e.getMessage());
            return result;
        }
        return result;
    }

    /**
     * 构建外部订单
     * @author daigb
     * @throws ParseException
     * @date:  2022-11-07 14:36
     */
    private OutOrderRequest buildJkyOutOrder(JkyOrderPushRequest.DeliveryOrder deliveryOrder,
                                             List<JkyOrderPushRequest.OrderLines> orderLines) throws ParseException {

        // 创建订单信息
        OutOrderRequest outOrderRequest = new OutOrderRequest();
        outOrderRequest.setOrderId(deliveryOrder.getDeliveryOrderCode());
        // 姓名
        outOrderRequest.setRealName(deliveryOrder.getBuyerName());
        // 身份证
        outOrderRequest.setIdCard(deliveryOrder.getIdcard());
        outOrderRequest.setUserPhone(deliveryOrder.getReceiverInfo().getMobile());
        // 区域类型
        outOrderRequest.setUserAddress(deliveryOrder.getReceiverInfo().getDetailAddress());
        outOrderRequest.setFreightPrice(deliveryOrder.getFreight());
        outOrderRequest.setOutOrderSource(OutOrderSourceEnum.JKY.getCode());
        if("CN".equals(deliveryOrder.getReceiverInfo().getCountryCode())){
            outOrderRequest.setAreaType(1);
        }else
        {
            outOrderRequest.setAreaType(3);
        }

        //订单商品总数
        int totalNum = 0;
        //订单总价
        BigDecimal totalPrice = BigDecimal.ZERO;
        List<OutOrderInfoRequest> outOrderInfoRequests = new ArrayList<>();

        for (JkyOrderPushRequest.OrderLines orderline : orderLines){
            totalNum += orderline.getPlanQty();
            totalPrice = orderline.getActualPrice().multiply(BigDecimal.valueOf(orderline.getPlanQty())).add(totalPrice);

            OutOrderInfoRequest outOrderInfoRequest = new OutOrderInfoRequest();

            outOrderInfoRequest.setBarCode(orderline.getItemCode());
            outOrderInfoRequest.setSourceSkuId(orderline.getItemCode());
            outOrderInfoRequest.setCartNum(orderline.getPlanQty());
            outOrderInfoRequest.setPrice(orderline.getActualPrice());
            OutOrderInfoRequest.Product product = new OutOrderInfoRequest.Product();
            OutOrderInfoRequest.Product.AttrInfo attrInfo = new OutOrderInfoRequest.Product.AttrInfo();
            attrInfo.setSuk(orderline.getItemName());
            attrInfo.setPrice(orderline.getActualPrice());
            attrInfo.setCost(orderline.getActualPrice());
            attrInfo.setOtPrice(orderline.getActualPrice());
            attrInfo.setTaxPrice(deliveryOrder.getTaxAmount());
            attrInfo.setTaxAndSecondPrice(deliveryOrder.getTaxAmount().add(deliveryOrder.getFreight()));
            product.setAttrInfo(attrInfo);
            outOrderInfoRequest.setProductInfo(product);
            outOrderInfoRequests.add(outOrderInfoRequest);

        }

        outOrderRequest.setTotalNum(totalNum);
        outOrderRequest.setTotalPrice(deliveryOrder.getTotalAmount());
        outOrderRequest.setTaxAmount(deliveryOrder.getTaxAmount());

        outOrderRequest.setPayPrice(deliveryOrder.getTotalAmount());
        outOrderRequest.setCreateTime(deliveryOrder.getCreateTime());
        outOrderRequest.setPayTime(deliveryOrder.getPayTime());
        outOrderRequest.setCreateName(deliveryOrder.getReceiverInfo().getName());

        outOrderRequest.setMark(deliveryOrder.getRemark());
        outOrderRequest.setProvince(deliveryOrder.getReceiverInfo().getProvince());
        outOrderRequest.setCity(deliveryOrder.getReceiverInfo().getCity());
        outOrderRequest.setDistrict(deliveryOrder.getReceiverInfo().getArea());
        outOrderRequest.setDetail(deliveryOrder.getReceiverInfo().getDetailAddress().split(" ")[deliveryOrder.getReceiverInfo().getDetailAddress().split(" ").length - 1]);
        outOrderRequest.setIsTof(true);

        outOrderRequest.setOutOrderInfoRequest(outOrderInfoRequests);

        return outOrderRequest;
    }
}
